package andorid.bignerdranch.com.photogallery.network;

import android.net.Uri;
import android.util.Log;

import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author luckku
 * @date 2021-12-06
 */
public class FlickrFetchr {

    public static final String TAG = "FlickrFetchr";
    public static final String API_KEY = "05e08e041d7865a8e75edf1a5331fa4f";

    /**
     * 从指定URL获取原始数据并返回一个字节流数组
     */
    public byte[] getUrlBytes(String urlSpec) throws IOException {
        URL url = new URL(urlSpec);
        //创建连接对象
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            //提交get请求，返回字节流数据  *若为post请求则调用getOutputStream()
            InputStream in = connection.getInputStream();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new IOException(connection.getResponseMessage() +
                        ": with " + urlSpec);
            }

            int byteRead;
            byte[] buffer = new byte[1024];
            //循环调用read方法读取网络数据
            while ((byteRead = in.read(buffer)) > 0) {
                //写入ByteArrayOutputStream字节数组中
                out.write(buffer, 0, byteRead);
            }
            //关闭网络连接
            out.close();
            return out.toByteArray();
        } finally {
            connection.disconnect();
        }
    }

    /**
     * 将getUrlBytes(String)方法返回的结果转换为String
     */
    public String getUrlString(String urlSpec) throws IOException {
        return new String(getUrlBytes(urlSpec));
    }

    public List<GalleryItem> fetchItems() {

        List<GalleryItem> items = new ArrayList<>();

        try {
            //builder类你真是太棒了！！
            String url = Uri.parse("http://api.flickr.ihdu.cn:8081/services/rest/")
                    .buildUpon()
                    .appendQueryParameter("method", "flickr.photos.getRecent")
                    .appendQueryParameter("api_key", API_KEY)
                    .appendQueryParameter("format", "json")
                    .appendQueryParameter("per_page", "30")
                    .appendQueryParameter("nojsoncallback", "1")
                    .appendQueryParameter("extras", "url_s")
                    .build().toString();
            String jsonString = getUrlString(url);
            Log.i(TAG, "Received JSON: " + jsonString);
            parseItems(items,jsonString);
        } catch (IOException ioe) {
            Log.e(TAG, "Failed to fetch items", ioe);
        }
        return items;
    }


    private void parseItems(List<GalleryItem> items, String jsonString) {
        Gson gson = new Gson();
        GalleryItemList galleryItemList = gson.fromJson(jsonString, GalleryItemList.class);
        List<GalleryItem> photoList = galleryItemList.getPhotos().getPhoto();
        items.addAll(photoList);
    }
}
